package ar.edu.uba.fi.jmit.receiver;

import java.util.LinkedList;
import java.util.List;

import ar.edu.uba.fi.jmit.receiver.mock.ReceiverFactoryMock;
import ar.edu.uba.fi.jmit.receiver.mock.ReceiverObserverMock;

public class ConsumerTaskTestCase extends ReceiverTestCase {
	
	@Override
	protected void setUp() throws Exception {
		ReceiverFactoryMock.useMock();
	}

	public void testConsume() {
		try {
			PollingConsumerHttpImpl consumer = new PollingConsumerHttpImpl();
			consumer.init();
			EventDispatcher dispatcher = new EventDispatcher(consumer);
			ReceiverObserverMock observerMock = new ReceiverObserverMock();
			dispatcher.addObserver(observerMock);
			assertEquals(0, consumer.getActualMessageCount());
			assertEquals(0, consumer.getTotalMessages());
			assertEquals(0, observerMock.getRecivedEventCount());
			consumer.service(createServletRequest(1), createServletResponse());
			Thread.sleep(50);
			assertEquals(0, consumer.getActualMessageCount());
			assertEquals(1, consumer.getTotalMessages());
			assertEquals(1, observerMock.getRecivedEventCount());
		} catch (Exception e) {
			fail(e);
		}
	}
	
	public void testManyObservers() {
		try {
			PollingConsumerHttpImpl consumer = new PollingConsumerHttpImpl();
			consumer.init();
			EventDispatcher dispatcher = new EventDispatcher(consumer);
			List<ReceiverObserverMock> observerMockList = new LinkedList<ReceiverObserverMock>();
			for(int i = 0; i < 20; i++) {
				observerMockList.add(new ReceiverObserverMock());
			}
			for(ReceiverObserverMock observerMock:observerMockList) {
				dispatcher.addObserver(observerMock);
			}
			assertEquals(0, consumer.getActualMessageCount());
			assertEquals(0, consumer.getTotalMessages());
			for(ReceiverObserverMock observerMock:observerMockList) {
				assertEquals(0, observerMock.getRecivedEventCount());
			}
			consumer.service(createServletRequest(1), createServletResponse());
			Thread.sleep(50);
			assertEquals(0, consumer.getActualMessageCount());
			assertEquals(1, consumer.getTotalMessages());
			for(ReceiverObserverMock observerMock:observerMockList) {
				assertEquals(1, observerMock.getRecivedEventCount());
			}
		} catch (Exception e) {
			fail(e);
		}
	}
}
